﻿package net.wangit.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public final class ZipFileUtil {

	private ZipFileUtil() {
	}

	public static File expandZipFile(File zipFile) throws IOException {
		String parent = zipFile.getParent();
		String dirName = zipFile.getName().split(".zip")[0];
		File directory = new File(parent, dirName);
		expandZipFile(zipFile, directory);
		return directory;
	}

	public static void expandZipFile(File zipFile, File target)
			throws IOException {
		ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
		ZipEntry entry;
		while ((entry = zipIn.getNextEntry()) != null)
			outputFileFromStream(zipIn, entry.getName(), target);
		zipIn.close();
	}

	private static void outputFileFromStream(InputStream in, String name,
			File parent) throws IOException {
		File outFile = new File(parent, name);
		(new File(outFile.getParent())).mkdirs();
		outFile.createNewFile();
		FileOutputStream out = new FileOutputStream(outFile);
		byte[] buf = new byte[0x20000];
		int len;
		while ((len = in.read(buf)) != -1){
			out.write(buf, 0, len);
		}
		out.close();
	}
}
